package com.atguigu.gulimail.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimail.to.UserInfoTo;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;
@Component
public class CartInterceptor implements HandlerInterceptor {
        //这里放一个ThreadLocal  目的是在同一个线程共享数据
    public static ThreadLocal<UserInfoTo> threadLocal=new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //  gulimail-auth-server 登录之后 就会往session里放LoginUser
            //userInfoTo主要是用来 判定购物车登录和没登录的状态的。
        UserInfoTo userInfoTo=new UserInfoTo();
        HttpSession session = request.getSession();
        MemberResponseVo member = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (member!=null) {
            // 如果 不为空。 则已经登录。
            // 封装一个TO对象。 专门用来存储用户id 和 session name=user-key的。

            userInfoTo.setId(member.getId());
        }
        Cookie[] cookies = request.getCookies();
        if (cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                userInfoTo.setUserKey(cookie.getValue());
                }
            }
        }
        if (StringUtils.isEmpty(userInfoTo.getUserKey())){
            String s = UUID.randomUUID().toString();
            userInfoTo.setUserKey(s);
        }
        threadLocal.set(userInfoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if (!userInfoTo.isTempUser()){
            userInfoTo.setTempUser(true);
            Cookie cookie=new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("gulimail.com");   //设置当前cookie的作用域
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);

            response.addCookie(cookie);
        }

    }
}
